package com.example.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

@Component
public class AuthFilter extends ZuulFilter {

    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    // 定义用户名和密码，实际应用中应该从配置文件或数据库中获取
    private static final String VALID_USERNAME = "admin";
    private static final String VALID_PASSWORD = "password123";

    /**
     * 过滤器类型：pre表示请求被路由之前执行
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器执行顺序：数字越小优先级越高
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否执行该过滤器：这里设置为true，表示对所有请求都执行过滤
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑：校验用户名和密码
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        log.info("校验请求: {} {}", request.getMethod(), request.getRequestURL().toString());

        // 从请求头或请求参数中获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 如果请求参数中没有，尝试从请求头中获取
        if (username == null || password == null) {
            username = request.getHeader("X-Username");
            password = request.getHeader("X-Password");
        }

        // 校验用户名和密码
        if (!validateCredentials(username, password)) {
            ctx.setSendZuulResponse(false); // 不进行路由
            ctx.setResponseStatusCode(401); // 设置响应状态码为401未授权

            try {
                // 设置响应体
                ctx.getResponse().setContentType("application/json");
                ctx.getResponse().getWriter().write("{\"message\":\"Unauthorized\"}");
            } catch (IOException e) {
                log.error("设置响应体失败", e);
            }

            log.warn("认证失败，用户名或密码不正确");
            return null;
        }

        log.info("认证成功");
        return null;
    }

    /**
     * 校验用户名和密码
     */
    private boolean validateCredentials(String username, String password) {
        return Objects.equals(username, VALID_USERNAME) &&
                Objects.equals(password, VALID_PASSWORD);
    }
}
